package com.lsk.common.interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.lsk.bean.WxBean;
import com.lsk.util.GlobalParameter;
import com.lsk.util.JsonUtil;
import com.lsk.util.MD5;
import com.lsk.util.UtilUUID;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * Created by Administrator on 2018/10/7.
 */
public class VerificationInterceptor implements Interceptor {
    Cache cache= Redis.use(PropKit.get("cache.name"));
    @Override
    public void intercept(Invocation inv) {
        Controller controller=inv.getController();
        HttpSession httpSession=inv.getController().getSession();
        Object admin_session_key=httpSession.getAttribute("admin_session_key");
        if (admin_session_key==null){//执行授权
            Map<String,String[]> map=controller.getParaMap();
            Record temp=new Record().set("parameters",map);
            String uuid= UtilUUID.getUUID();
            cache.setex(uuid,60*60*24,temp);
            String url=getAuthorizationUrl(uuid);
            controller.redirect(url);
        }else {
            inv.invoke();
        }

    }


    /*用户授权*/
    private String getAuthorizationUrl(String uuid){
        String appId="";
        WxBean wxBean=new WxBean();
        appId=wxBean.getAppId();
        Record temp=cache.get(uuid);
        temp.set("appId",appId);
        cache.setex(uuid,60*60*24,temp);
        String url= SnsAccessTokenApi.getAuthorizeURL(appId,
                "http://"+ GlobalParameter.domain+"/mobileMarketing/verificationAuthorization",
                uuid,false);
        return url;
    }

}
